﻿using ciji.Application;
using ciji.Core;
using Furion;
using Furion.Authorization;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace ciji.Web.Core
{
    public class JwtHandler : AppAuthorizeHandler
    {
        /// <summary>
        /// 请求管道
        /// </summary>
        /// <param name="context"></param>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {

            var userId = UserHelper.GetUserId();
            var changeTime = App.GetService<ISysCacheService>().Get<long>(CacheConst.KeyTokenChange + userId);
            var tokenTime = UserHelper.GetTokenTime();
            if (changeTime > tokenTime)
            {
                UnifyContext.Fill(401);
                return Task.FromResult(false);
            }
            // 检查权限，如果方法时异步的就不用 Task.FromResult 包裹，直接使用 async/await 即可
            return Task.FromResult(CheckAuthorzie(httpContext));

        }
        /// <summary>
        /// 检查权限
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        private static bool CheckAuthorzie(DefaultHttpContext httpContext)
        {
            // 获取权限特性
            var securityDefineAttribute = httpContext.GetMetadata<SecurityDefineAttribute>();
            if (securityDefineAttribute == null) return true;

            var resourceId = securityDefineAttribute.ResourceId;
            var resourceIds = resourceId.Split(',');


            if (App.User == null)
            {
                return false;
            }
            else
            {
                var securities = App.GetService<RBACService>().GetPermission();
                foreach (var item in resourceIds)
                {
                    if (securities.Contains(item))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}